package com.hucheng.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.security.MessageDigest;

/**
 * @Author: 凉白开不加冰
 * @Version: 0.0.1V
 * @Date: 2019-06-26
 * @Description: 类描述
 **/
@Slf4j
public class MD5Utils {
    private static final int BUFFERSIZE = 8196;
    private static final String ALGORITHM = "MD5";
    private static final String CHARSET = "UTF-8";

    public MD5Utils() {
    }

    public static String md5(String input) {
        return md5(input, CHARSET);
    }

    private static String md5(String input, String charsetName) {
        try {
            MessageDigest md5 = MessageDigest.getInstance(ALGORITHM);
            byte md5Bytes[] = md5.digest(input.getBytes(charsetName));
            return StringUtils.getInstance().byte2hex(md5Bytes);
        } catch (Exception e) {
            log.error((new StringBuilder(String.valueOf(CommonUtils
                    .getTraceInfo()))).append(e.getMessage()).toString());
        }
        return input;
    }

    public static String md5file(String filename)
    {
        BufferedInputStream bufferedInputStream = null;
        MessageDigest md;
        try {
            bufferedInputStream = new BufferedInputStream(new FileInputStream(filename), BUFFERSIZE);
            md = MessageDigest.getInstance(ALGORITHM);
            byte[] buffer = new byte[BUFFERSIZE];
            int i = 0;
            while((i = bufferedInputStream.read(buffer)) != -1){
                md.update(buffer, 0, i);
            }
            return StringUtils.getInstance().byte2hex(md.digest());
        } catch (Exception e) {
            log.error(CommonUtils.getTraceInfo() +" filename:"+filename+"\t"+ StringUtils.getInstance().nullToStrTrim(e.getMessage()));
            return null;
        }finally {
            WebUtils.getInstance().closeBufferedInputStream(bufferedInputStream);
        }
    }

    public static String md5reverse(String md5) {
        return "";
    }
}
